import React, { useState, useEffect, Key } from 'react'
import {
  Row,
  Col,
  Radio,
  Modal,
  message,
  Button,
  Form,
  Input,
  Table,
  Upload,
} from 'antd'
import type { ColumnsType } from 'antd/lib/table'
import { UploadOutlined } from '@ant-design/icons'
import type { RadioChangeEvent, UploadProps } from 'antd' //引入的组件
import fileDownload from 'js-file-download'

import { DataSourceType, WhiteNameList } from './lotteryWhiteList' //引入的自定义内容
import { SendPageByCandidateQuery } from '@/services/index.d'
import commonStyle from '@/pages/publicStyle'
import {
  sendUpdateByCondition,
  sendDownloadCandidateTemplate,
  sendPageByCandidateQuery,
} from '@/services/index'
import { baseUrl, FetchUrl } from '@/services/url'
import './index.less'

const {
  pb50,
  mr30,
  pb10,
  ml10,
  colorC8,
  mt20,
  mr50,
  ml20,
  mr10,
  mb20,
  title3,
} = commonStyle
const { Item } = Form
interface IProps {
  location: {
    state: {
      record: DataSourceType
    }
  }
}

export default function SetWhiteList(props: IProps) {
  const {
    location: {
      state: { record },
    },
  } = props

  const [isModalVisible, setIsModalVisible] = useState(false)
  const [total, setTotal] = useState(0)
  const [dataSource, setDataSource] = useState<WhiteNameList[]>([])
  const [params, setParams] = useState<SendPageByCandidateQuery>({
    activityBasicId: record.activityBasicId,
    mobile: '',
    page: 1,
    pageSize: 10,
    userName: '',
  })

  const [radioValue, setRadioValue] = useState(record.isEveryoneExpose)
  const [userModel, setUserModel] = useState(record.isEveryoneExpose)
  const [checkedList, setCheckedList] = useState<Key[]>([])

  const handleOk = () => {
    const params = {
      activityBasicId: record!.activityBasicId,
      isEveryoneExpose: radioValue,
    }
    sendUpdateByCondition(params) //发起请求,
      .then(res => {
        console.log(res)
        message.success('修改成功')
        setUserModel(radioValue) //请求成功的时候,把展示用户模式跟radio的值匹配
      })
      .finally(() => {
        setIsModalVisible(false) //关闭弹窗
      })
  }

  const handleCancel = () => {
    setIsModalVisible(false)
  }

  useEffect(() => {
    //发起请求,依赖params里面的数据
    sendPageByCandidateQuery(params).then(res => {
      const { data } = res

      setDataSource(data.rows)
      setTotal(data.total)
    })
  }, [params.userName, params.mobile, params.page, params.pageSize])

  useEffect(() => {
    setUserModel(record.isEveryoneExpose)
  }, [record.isEveryoneExpose])

  const onChange = (e: RadioChangeEvent) => {
    setRadioValue(e.target.value)
  }
  function handleFormFinish(values: {
    userName: string | undefined
    mobile: string | undefined
  }) {
    console.log(values)
    const newParams = { ...params }
    newParams.userName = values.userName || ''
    newParams.mobile = values.mobile
    newParams.page = 1 //搜索重置页数
    setParams(newParams)
  }
  function handleFormReset() {
    const newParams = { ...params }
    newParams.userName = ''
    newParams.mobile = ''
    newParams.page = 1 //重置数据
    setParams(newParams)
  }
  function tablePageChange(page: number, size: number) {
    const newParams = { ...params }
    newParams.page = page
    setParams(newParams)
    // console.log('页数改变', size, page);
  }
  function rowSelectionChange(ids: Key[], items: WhiteNameList[]) {
    console.log(ids, items)
    setCheckedList(ids)
  }

  function handleDownloadFile() {
    sendDownloadCandidateTemplate({
      file: checkedList,
      activityBasicId: record.activityBasicId,
    }).then(res => {
      fileDownload(res.data, record.activityName + '.xlsx')
      console.log(res)
    })
  }

  return (
    <div className="white-list-set">
      <div className="white-list-set-top">
        <Row>
          <Col className="white-list-title" style={{ ...pb10, ...title3 }}>
            设置白名单
          </Col>
        </Row>
        {showForm.map(item => (
          <Row key={item.label}>
            <Col style={item.style}>{item.label}</Col>
            <Col>{record[item.recordLabel]}</Col>
          </Row>
        ))}

        <Row>
          <Col style={{ width: '3rem', ...colorC8, ...pb50 }}>公开方式</Col>
          <Col style={mr30}>{record!.isEveryoneExposeLabel}</Col>
          <Col>
            <a
              onClick={() => {
                setIsModalVisible(true)
              }}
            >
              修改设置
            </a>
          </Col>
        </Row>
      </div>

      <div className="white-list-none-block" />
      {userModel ? (
        <Button style={{ marginTop: '0.5rem' }}>返回</Button>
      ) : (
        <div>
          <Row style={{ marginTop: '0.5rem' }}>
            <Col className="white-list-title" style={{ ...title3, ...mt20 }}>
              抽奖白名单
            </Col>
          </Row>

          <Form onFinish={handleFormFinish}>
            <Row style={mt20}>
              <Col>
                <Item name="userName" label="姓名" style={mr30}>
                  <Input placeholder="请输入" />
                </Item>
              </Col>

              <Col style={mr50}>
                <Item name="mobile" label="手机号">
                  <Input placeholder="请输入" />
                </Item>
              </Col>
              <Col>
                <Button type="primary" style={mr10} htmlType="submit">
                  搜索
                </Button>
                <Button htmlType="reset" onClick={handleFormReset}>
                  重置
                </Button>
              </Col>
            </Row>
          </Form>
          <Row align="middle" style={mb20}>
            <Upload {...uploadProps}>
              <Button icon={<UploadOutlined />} type="primary">
                导入
              </Button>
            </Upload>
            <Button
              style={{ ...mr10, ...ml20 }}
              onClick={() => {
                message.info('暂无接口')
              }}
            >
              删除
            </Button>
            <a style={mr30} onClick={handleDownloadFile}>
              下载导入模板
            </a>
            {/* <a>查看导入进度</a> */}
          </Row>
          <Table
            rowSelection={{
              checkStrictly: true,
              onChange: rowSelectionChange,
              selectedRowKeys: checkedList,
            }}
            columns={columns}
            dataSource={dataSource}
            rowKey={record => record.id}
            pagination={{
              total,
              showTotal: () => `共 ${total} 条`,
              onChange: tablePageChange,
              pageSize: params.pageSize,
            }}
          />
        </div>
      )}

      <Modal
        title="Basic Modal"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        destroyOnClose
      >
        <p>
          公开方式 :
          <Radio.Group onChange={onChange} value={radioValue} style={ml10}>
            {radioArr.map(item => (
              <Radio value={item.radioValue} key={item.label}>
                {item.label}
              </Radio>
            ))}
          </Radio.Group>
        </p>
      </Modal>
    </div>
  )
}
const showForm = [
  {
    style: { width: '3rem', ...colorC8, ...pb10 },
    label: '活动名称',
    recordLabel: 'activityName',
  },
  {
    style: { width: '3rem', ...colorC8, ...pb10 },
    label: '活动状态',
    recordLabel: 'activityStatusLabel',
  },
  {
    style: { width: '3rem', ...colorC8, ...pb10 },
    label: '抽奖活动时间',
    recordLabel: 'activityTime',
  },
]
const radioArr = [
  { radioValue: true, label: '所有用户' },
  { radioValue: false, label: '白名单用户' },
]
const columns: ColumnsType<WhiteNameList> = [
  {
    title: '姓名',
    dataIndex: 'userName',
    key: 'userName',
  },
  {
    title: '手机号',
    dataIndex: 'mobile',
    key: 'mobile',
  },
  {
    title: '创建时间',
    dataIndex: 'gmtCreated',
    key: 'gmtCreated',
  },
]
const uploadProps: UploadProps = {
  name: 'file',
  action: baseUrl + FetchUrl.downloadCandidateTemplate,
  headers: {
    authorization: 'authorization-text',
  },
  showUploadList: false,
  onChange(info) {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList)
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 文件上传成功`)
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`)
    }
  },
}
